﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Net;

namespace iReaper
{
    public partial class log : System.Web.UI.Page
    {
        public override void ProcessRequest(HttpContext context)
        {
            NameValueCollection queryString = context.Request.QueryString;
            string strCourseID = queryString["CourseID"];
            string strType = queryString["Type"];
            string strUserID = queryString["UserID"];

            if (string.IsNullOrEmpty(strCourseID) ||
                string.IsNullOrEmpty(strType) ||
                string.IsNullOrEmpty(strUserID)
                )
            {
                return;
            }

            int courseId;
            Guid userId;
            if (!int.TryParse(strCourseID, out courseId))
            {
                return;
            }

            userId = new Guid(strUserID);

            FileType type = FileType.None;
            try
            {
                type = (FileType)Enum.Parse(typeof(FileType), strType);
            }
            catch { }
            LogRequest request = new LogRequest(courseId);
            request.CourseType = (int)type;
            request.UserID = userId;

            // Get user address
            string ip = context.Request.Params["HTTP_X_FORWARDED_FOR"];
            if (ip != null)
            {
                string addr = ip.Split(':')[0];
                request.IP = IPAddress.Parse(addr).Address;
            }
            else
            {
                request.IP = IPAddress.Parse(context.Request.UserHostAddress).Address;
            }
            // Get iReaper version
            request.UserAgent = context.Request.Params["HTTP_USER_AGENT"];
            if (string.IsNullOrEmpty(request.UserAgent))
            {
                request.UserAgent = context.Request.UserAgent;
            }
            LogManager.AddRequest(request);
        }
    }
}
